package com.supostacks.application.application.impl;

import com.alibaba.fastjson.JSONObject;
import com.supostacks.application.server.es.EsResourceInfoRepository;
import com.supostacks.application.application.IResourceInfoApplication;
import com.supostacks.domain.repository.IResourceInfoRepository;
import com.supostacks.domain.vo.BaseVo;
import com.supostacks.domain.vo.ResourceInfoVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ResourceInfoApplicationImpl implements IResourceInfoApplication {

    @Resource
    private IResourceInfoRepository resourceInfoRepository;

    @Resource
    EsResourceInfoRepository esResourceInfoRepository;

    @Override
    public String insert(JSONObject data) {
        ResourceInfoVo categoryVo = JSONObject.toJavaObject(data, ResourceInfoVo.class);
        String id = resourceInfoRepository.insert(categoryVo);
        if (StringUtils.hasText(id) && !"会员介绍".equals(categoryVo.getType())) {
                esResourceInfoRepository.save(categoryVo);
        }
        return id;
    }

    @Override
    public void deleteById(String id) {
        resourceInfoRepository.deleteById(id);
        esResourceInfoRepository.deleteById(id);
    }

    @Override
    public String updateById(JSONObject data) {
        ResourceInfoVo categoryVo = JSONObject.toJavaObject(data, ResourceInfoVo.class);
        String id = resourceInfoRepository.updateById(categoryVo);
        if (StringUtils.hasText(id) && !"会员介绍".equals(categoryVo.getType())) {
            esResourceInfoRepository.deleteById(id);
            esResourceInfoRepository.save(categoryVo);
        }
        return id;
    }

    @Override
    public BaseVo selectById(String id) {
        return resourceInfoRepository.selectById(id);
    }

    @Override
    public List<BaseVo> selectList(JSONObject param) {
        List<ResourceInfoVo> resourceInfoVos = resourceInfoRepository.selectList(param);
        return new ArrayList<>(resourceInfoVos);
    }

    @Override
    public JSONObject selectByPage(JSONObject options, int pageNo, int pageSize) {
        return resourceInfoRepository.selectByPage(options, pageNo, pageSize);
    }

    @Override
    public List<BaseVo> search(JSONObject option) {
        return esResourceInfoRepository.search(option);
    }
}
